<?php
class Page{
	//一列数量
	public $colNum;
	//总数
	public $count;
	//总页数
	public $pageCount;
	//当前页数
	public $nowPage;
	//偏移数
	public $offestPage;
	//完整URL
	public $thisUrl;
	//显示页码个数
	public $pageRoll;

	/**
	 * 初始化分页类的各种参数
	 *@param $[colNum]  [单页数据数量]
	 *@param $[count]   [数据总数]
	 *@param $[roll]    [分页码显示数量]
	 *@return           []
	 */
	public function __construct($colNum,$count,$roll){
		//显示多少个分页数字
		$this->pageRoll = $roll;
		//一页多少条记录
		$this->colNum = $colNum;
		//得到当前页面url
		$this->thisUrl = $_SERVER["REQUEST_URI"];
		//计算总页数
		$this->pageCount = ceil($count/$colNum);

		//处理当前页
		if(empty($_GET['p'])||$_GET['p']<0 || !is_numeric($_GET['p'])){
			$this->nowPage = 1;
		}else if($_GET['p']>$this->pageCount){
			$this->nowPage = $this->pageCount;
		}else{
			$this->nowPage = (int)$_GET['p'];
		}

		//计算偏移量
		$this->offestPage = ($this->nowPage-1)*$this->colNum;
	}

	/**
	 *处理分页逻辑生成分页代码
	 *@return [str:前端代码分页 html]
	 */
	public function show(){
		//没有数据  退出
		if( $this->pageCount == 0 ){
			return '';
		}
		$html = '当前页码：';
		//分析当前url
		$par = parse_url( $this->thisUrl );
		//当前页码  ceil  取整
		$nowCool = ceil( $this->nowPage/$this->pageRoll );

		//url有参数的情况
		if( isset( $par['query'] ) ){
			parse_str( $par['query'],$par_array );
			unset( $par_array['p'] );
			$this->thisUrl = $par['path'].'?'.http_build_query( $par_array ).'&';
		}else{
			//url 无参数情况
			$this->thisUrl = $par['path'].'?';
		}

		//上一页判断
		if( $this->nowPage > 1 ){
			$html .= '<a href = '.$this->thisUrl.'p='.($this->nowPage-1).'>'.'上一页'.'</a> &nbsp &nbsp &nbsp' ;
		}
		for( $i = 1;$i <= $this->pageRoll;$i++ ){
			// echo $nowCool.'---'.$this->nowPage;
			$page = ($nowCool -1)*$this->pageRoll+$i;
			if ($this->pageCount >= $page) {
				if($this->nowPage == $page) {
					$html .= '<span style="color:red;">'.$page.'</span>&nbsp &nbsp &nbsp' ;
				} else {
					$html .= '<a href = '.$this->thisUrl.'p='.$page.'>'.$page.'</a>&nbsp &nbsp &nbsp' ;
				}
			}
		}
		//一页判断
		if( $this->nowPage < $this->pageCount ){
			$html .= '<a href = '.$this->thisUrl.'p='.($this->nowPage+1).'>'.'下一页'.'</a>&nbsp &nbsp &nbsp' ;
		}
		return $html;
	}
}
